package com.sso.gateway.client;

import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import com.sso.gateway.client.UserInfo;

@Slf4j
@Component
public class AuthServiceClient {
    private final WebClient.Builder webClientBuilder;

    public AuthServiceClient(WebClient.Builder webClientBuilder) {
        this.webClientBuilder = webClientBuilder;
    }

    public Mono<Boolean> validateTokenWithAuthService(String token) {
        if (!StringUtils.hasText(token)) {
            return Mono.just(false);
        }
        return webClientBuilder
                .build()
                .post()
                .uri("lb://sso-auth-service/auth/validate")
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
                .retrieve()
                .bodyToMono(Boolean.class)
                .onErrorResume(ex -> {
                    log.warn("调用认证服务验证令牌失败: {}", ex.getMessage());
                    return Mono.just(false);
                });
    }

    public Mono<UserInfo> fetchUserInfoFromAuthService(String token) {
        return webClientBuilder
                .build()
                .get()
                .uri("lb://sso-auth-service/auth/userinfo")
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
                .retrieve()
                .bodyToMono(UserInfo.class)
                .onErrorResume(ex -> {
                    log.warn("获取用户信息失败: {}", ex.getMessage());
                    return Mono.empty();
                });
    }
}
